import "reflect-metadata";

// 全局测试设置
beforeAll(() => {
  // 设置测试环境
  process.env.NODE_ENV = "test";

  // 设置测试超时
  jest.setTimeout(10000);

  console.log("🚀 测试环境初始化完成");
});

afterAll(() => {
  console.log("🏁 所有测试完成");
});

// 全局测试工具函数
(global as any).testUtils = {
  // 创建模拟数据
  createMockData: (type: string, overrides: any = {}) => {
    const baseData: Record<string, any> = {
      character: {
        id: 2001,
        name: "测试角色",
        roleType: 1,
        sex: 1,
        lvl: 1,
        exp: 0,
        trans: 0,
        title: "",
        vip: 0,
        headImg: "",
        allowLogin: 1,
        objType: 0,
        indexID: 0,
        userId: 1,
      },
      user: {
        id: 1,
        username: "testuser",
        email: "test@example.com",
        accessToken: "mock-token",
      },
    };

    return { ...baseData[type], ...overrides };
  },

  // 验证响应格式
  validateResponse: (response: any, expectedCode: number = 0) => {
    expect(response).toBeDefined();
    expect(typeof response).toBe("object");
    expect(response).toHaveProperty("code");
    expect(response.code).toBe(expectedCode);
  },

  // 验证错误响应
  validateErrorResponse: (response: any, expectedCode: number = -1) => {
    expect(response).toBeDefined();
    expect(typeof response).toBe("object");
    expect(response).toHaveProperty("code");
    expect(response).toHaveProperty("msg");
    expect(response.code).toBe(expectedCode);
    expect(typeof response.msg).toBe("string");
    expect(response.msg.length).toBeGreaterThan(0);
  },

  // 验证成功响应
  validateSuccessResponse: (response: any) => {
    expect(response).toBeDefined();
    expect(typeof response).toBe("object");
    expect(response).toHaveProperty("code");
    expect(response.code).toBe(0);
    expect(response).toHaveProperty("data");
  },

  // 日志记录
  logTest: (testName: string, payload: any, response: any) => {
    console.log(`\n🧪 ${testName}`);
    console.log("📤 请求参数:", JSON.stringify(payload, null, 2));
    console.log("📥 返回结果:", JSON.stringify(response, null, 2));
    console.log("---");
  },

  // 性能测试
  measurePerformance: async (
    fn: () => Promise<any>,
    iterations: number = 100
  ) => {
    const startTime = Date.now();
    const results = [];

    for (let i = 0; i < iterations; i++) {
      const result = await fn();
      results.push(result);
    }

    const endTime = Date.now();
    const totalTime = endTime - startTime;
    const avgTime = totalTime / iterations;

    console.log(`⏱️ 性能测试结果:`);
    console.log(`   总执行时间: ${totalTime}ms`);
    console.log(`   平均执行时间: ${avgTime.toFixed(2)}ms`);
    console.log(`   执行次数: ${iterations}`);

    return {
      totalTime,
      avgTime,
      results,
    };
  },
};

// 类型声明
declare global {
  namespace NodeJS {
    interface Global {
      testUtils: {
        createMockData: (type: string, overrides?: any) => any;
        validateResponse: (response: any, expectedCode?: number) => void;
        validateErrorResponse: (response: any, expectedCode?: number) => void;
        validateSuccessResponse: (response: any) => void;
        logTest: (testName: string, payload: any, response: any) => void;
        measurePerformance: (
          fn: () => Promise<any>,
          iterations?: number
        ) => Promise<any>;
      };
    }
  }
}
